import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static java.util.Arrays.copyOf;

// key-value 模型
public class HashBucket {
    private static class Node {
        private int key;
        private int value;
        Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小


    /**
     * 给哈希表进行添加
     * @param key
     * @param value
     * @return
     */
    public void put(int key, int value) {

        int index = key % array.length;
        Node cur = array[index];
        if(size == 0){
            cur = new Node(key,value);
            size++;
        }

        while (cur.next != null){
            if(cur.key == key){
                cur.value = value;
                return;
            }
            cur = cur.next;
        }
        cur = new Node(key,value);
        size++;

        if(loadFactor() > LOAD_FACTOR){
            resize();
        }
    }


    /**
     * 扩容
     */
    private void resize() {
        Node[] newArray = new Node[array.length * 2];

        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null){
                int newIndex = cur.key % newArray.length;
                Node curN = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }

        array = newArray;
    }


    private double loadFactor() {
        return size * 1.0 / array.length;
    }


    public HashBucket() {
        array = new Node[DEFAULT_SIZE];
    }


    public int getval(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur.next != null){
            if(cur.key == key){
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
    }
}